package com.grape.juc.safe.sync;

/**
 * 描述:同步方法使用的锁证明
 * @author: myx
 * @date: 2019-05-05
 * Copyright © 2019-grape. All rights reserved.
 */
public class SyncMethod{
    public static void main(String[] args) throws InterruptedException {
        Thread002 thread002 = new Thread002();
        Thread t1 = new Thread(thread002, "窗口1");
        Thread t2 = new Thread(thread002, "窗口2");
        t1.start();
        Thread.sleep(40);
        thread002.flag = false;
        t2.start();

    }
}

/**
 * 描述:线程实现
 * @author: myx
 * @date: 2019-05-05
 * Copyright © 2019-grape. All rights reserved.
 */
class Thread002 implements Runnable{
    private int trainCount = 100;
    private Object oj = new Object();
    public boolean flag = true;

    @Override
    public void run() {
        if (flag) {
            while (trainCount > 0) {
                synchronized (this) {
                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                    if (trainCount > 0) {
                        System.out.println(Thread.currentThread().getName() + "," + "出售第" + (100 - trainCount + 1) + "票");
                        trainCount--;
                    }
                }

            }
        } else {
            while (trainCount > 0) {
                sale();
            }
        }
    }
    public synchronized void sale() {
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
        if (trainCount > 0) {
            System.out.println(Thread.currentThread().getName() + "," + "出售第" + (100 - trainCount + 1) + "票");
            trainCount--;
        }

    }
}
